package com.oj.ojcodesandbox.utils;

import cn.hutool.core.date.StopWatch;
import com.oj.ojcodesandbox.model.ExecuteMessage;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 执行进程工具类
 */
public class ProcessUtils {
    /**
     * 执行进程并获取信息
     * @param compileProcess
     * @return
     */
    public static ExecuteMessage runProcessAndGetMessage(Process compileProcess, String optionNam){
        ExecuteMessage executeMessage = new ExecuteMessage();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try {
            int exitValue = compileProcess.waitFor();
            executeMessage.setExitValue(exitValue);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()));
            if (exitValue==0){
                System.out.println(optionNam + "成功");
                //分批获取进程的正常输出
                StringBuilder compileOutputStringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null){
                    compileOutputStringBuilder.append(line);
                }
                executeMessage.setMessage(compileOutputStringBuilder.toString());
            }else {
                System.out.println(optionNam + "失败，错误码：" + exitValue);
                //分批获取进程的正常输出
                StringBuilder compileOutputStringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null){
                    compileOutputStringBuilder.append(line);
                }
                executeMessage.setMessage(compileOutputStringBuilder.toString());
                //分批获取进程的错误输出
                BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(compileProcess.getErrorStream()));
                StringBuilder errorCompileOutputStringBuilder = new StringBuilder();
                String errorLine;
                while ((errorLine = errorBufferedReader.readLine()) != null){
                    errorCompileOutputStringBuilder.append(errorLine);
                }
                executeMessage.setErrorMessage(errorCompileOutputStringBuilder.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        stopWatch.stop();
        executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
        return executeMessage;
    }
}
